<template>
	<div class="sys-pos-container">
		<el-card shadow="hover">
			<el-form :model="state.queryParams" ref="queryForm" :inline="true">
				<el-form-item :label-width='70' label="客户">
					<el-select :clearable='true' class='ml10' v-model="state.queryParams.customerId" placeholder="请选择" filterable >
						<el-option v-for='item in state.customerDict' :key='item.value' :label='item.label'
							:value='item.value' />
					</el-select>
				</el-form-item>
				<el-form-item :label-width='70' label='省份'>
					<el-select :clearable='true' class='ml10' v-model='state.queryParams.province' placeholder='请选择' filterable >
						<el-option v-for='item in optionDict.provinceDict' :key='item.value' :label='item.label'
							:value='item.value' />
					</el-select>
				</el-form-item>
				<el-form-item :label-width='70' label="城市" prop="city">
					<el-input placeholder="城市" clearable class='ml10' @keyup.enter="handleQuery"
						v-model="state.queryParams.city" />
				</el-form-item>
				<el-form-item :label-width='70' label='运营商'>
					<el-select :clearable='true' class='ml10' v-model='state.queryParams.operatorPlatform'
						placeholder='请选择'>
						<el-option v-for='item in optionDict.operatorPlatformDict' :key='item.value' :label='item.label'
							:value='item.value' />
					</el-select>
				</el-form-item>
				<el-form-item :label-width='70' label="产品名称" prop="productName">
					<el-input placeholder="产品名称" clearable class='ml10' @keyup.enter="handleQuery"
						v-model="state.queryParams.productName" />
				</el-form-item>
				<el-form-item :label-width='70' label="Pid" prop="pid">
					<el-input placeholder="Pid" clearable class='ml10' @keyup.enter="handleQuery"
						v-model="state.queryParams.pid" />
				</el-form-item>
				<el-form-item :label-width='70' label="手机号码" prop="phone">
					<el-input placeholder="手机号码" clearable class='ml10' @keyup.enter="handleQuery"
						v-model="state.queryParams.phone" />
				</el-form-item>
				<el-form-item :label-width='70' label="发送响应" prop="sendSMSData">
					<el-input class='ml10' placeholder="发送短信响应" clearable @keyup.enter="handleQuery"
						v-model="state.queryParams.sendSMSData" />
				</el-form-item>
				<el-form-item :label-width='70' label="验证响应" prop="verifySMSData">
					<el-input class='ml10' placeholder="验证短信响应" clearable @keyup.enter="handleQuery"
						v-model="state.queryParams.verifySMSData" />
				</el-form-item>
				<el-form-item :label-width='70' label='日期'>
					<el-date-picker class='ml10' v-model='state.UTCDateRange' type='daterange' range-separator='至'
						start-placeholder='开始日期' end-placeholder='结束日期' :shortcuts='shortcuts' :disabled-date="disabledDate"
						@keyup.enter="handleQuery" />
				</el-form-item>
				<el-form-item>
					<el-button-group>
						<el-button type="primary" icon="ele-Search" @click="handleQuery"
							v-auth="'diRequestSmsRecord:query'"> 查询 </el-button>
						<el-button icon="ele-Refresh" @click="resetQuery" v-auth="'diRequestSmsRecord:query'"> 重置
						</el-button>
					</el-button-group>
                    <el-button icon="ele-FolderOpened" @click="exportExcel"> 导出 </el-button>
				</el-form-item>
			</el-form>
		</el-card>

		<el-card shadow="hover" style="margin-top: 8px">
			<el-table :data="state.data" class='w100' v-loading="state.loading" border stripe highlight-current-row fit @cell-mouse-enter="TransferIn"  @cell-mouse-leave="mark">
				<el-table-column header-align='center' prop="createTime" label="请求时间" align="center" width="160"
					show-overflow-tooltip />
				<el-table-column header-align='center' prop="pid" label="Pid" show-overflow-tooltip align="center" width="200" />
				<el-table-column header-align='center' prop="customerName" label="客户" show-overflow-tooltip width="100"   />
				<el-table-column header-align='center' prop="productName" label="媒体产品" show-overflow-tooltip width="220" />
				<el-table-column header-align='center' prop="phoneC" width="115" label="手机号码" align="center" show-overflow-tooltip/>
				<el-table-column header-align='center' prop='province' width="82" label="省份" align="center" show-overflow-tooltip/>
				<el-table-column header-align='center' prop="city" width="82" label="城市" align="center" show-overflow-tooltip />
				<el-table-column header-align='center' label="运营商" align="center" show-overflow-tooltip  width="82">
					<template #default="scope">
						<el-tag type="success" v-if="scope.row.operatorPlatform === 1">移动</el-tag>
						<el-tag type="warning" v-else-if="scope.row.operatorPlatform === 2">联通</el-tag>
						<el-tag type="info" v-else-if="scope.row.operatorPlatform === 3">电信</el-tag>
						<el-tag type="error" v-else-if="scope.row.operatorPlatform === 4">广电</el-tag>
						<el-tag type="success" v-else-if="scope.row.operatorPlatform === 5">移动虚拟运营商</el-tag>
						<el-tag type="warning" v-else-if="scope.row.operatorPlatform === 6">联通虚拟运营商</el-tag>
						<el-tag type="info" v-else-if="scope.row.operatorPlatform === 7">电信虚拟运营商</el-tag>
						<el-tag type="error" v-else>未知</el-tag>
					</template>
				</el-table-column>
				<el-table-column header-align='center' prop="resData" label="发送验证码响应" min-width="160" show-overflow-tooltip>
					<template #default="scope">
						<el-text :type='scope.row.resData?.indexOf("0000") == -1 ? "danger" : "success"'>{{
							scope.row.resData }}</el-text>
					</template>
				</el-table-column>
				<el-table-column header-align='center' prop="onceVerifyResData" label="提交验证码响应" min-width="160" show-overflow-tooltip>
					<template #default="scope">
						<el-text :type='scope.row.onceVerifyResData?.indexOf(":\"0000\"") == -1 ? "danger" : "success"'>{{
							scope.row.onceVerifyResData }}</el-text>
					</template>
				</el-table-column>
				<el-table-column header-align='center' prop="onceVerifyCode" label="验证码" align="right" width="80"
					show-overflow-tooltip />
				<el-table-column label="操作" width="80" align="center" fixed="right" show-overflow-tooltip>
					<template #default="scope">
						<el-button size="small" text type="danger" @click="delDiBusiness(scope.row)"
							v-auth="'diBusiness:delete'"> 详情 </el-button>
					</template>
				</el-table-column>
			</el-table>
			<el-pagination @size-change="onHandleSizeChange" @current-change="onHandleCurrentChange" class="mt15"
				:page-sizes="[20, 50, 100]" v-model:current-page="state.queryParams.pageNum" background
				v-model:page-size="state.queryParams.pageSize" layout="total, sizes, prev, pager, next, jumper"
				:total="state.total">
			</el-pagination>
		</el-card>
		<editDiRequestSmsRecord ref="editDieditDiRequestSmsRecordRef" :title="state.editTitle" />
	</div>
</template>

<script lang="ts" setup name="diRequestSmsRecord">
import { onMounted, onUnmounted, reactive, ref } from 'vue';
import { ElMessageBox, ElMessage } from 'element-plus';
import { optionDict } from '/@/const/dict.ts';
import mittBus from '/@/utils/mitt';
import { convertLocalDate, datePickerShortcuts } from '/@/utils/formatTime'
import { getFileName, downloadByData } from '/@/utils/download';
import SysDiCustomerApi from '/@/api/delivery/customer';
import { DiRequestSmsRecord } from '/@/api/models';
import SysDiRequestSmsRecordApi from '/@/api/delivery/requestSmsRecord';
import editDiRequestSmsRecord from './component/editDiRequestSmsRecord.vue';
import SysDiCustomerProductOrderApi from "/@/api/delivery/customerProductOrder";

// 定义变量内容
const editDieditDiRequestSmsRecordRef = ref<InstanceType<typeof editDiRequestSmsRecord>>();
// 定义变量内容
const shortcuts = datePickerShortcuts();
const state = reactive({
	loading: false,
	data: [] as Array<DiRequestSmsRecord>,
	UTCDateRange: [new Date(), new Date()],
	total: 0 as any,
	queryParams: {
		pid: undefined,
		phone: undefined,
		province: undefined,
		productName: undefined,
		operatorPlatform: undefined,
		sendSMSData: undefined,
		verifySMSData: undefined,
		dateRange: [],
		customerId: undefined,
		pageNum: 1,
		pageSize: 20,
	},
	editTitle: '',
	customerDict: [],
});

onMounted(async () => {
	mittBus.on('submitRefresh', () => {
		handleQuery();
	});
	await customerDictQuery();
});

onUnmounted(() => {
	mittBus.off('submitRefresh');
});

const formatLocalDate = async () => {
	if (state.UTCDateRange[0] as string)
		state.UTCDateRange[0] = new Date(state.UTCDateRange[0]);
	if (state.UTCDateRange[1] as string)
		state.UTCDateRange[1] = new Date(state.UTCDateRange[1]);

	if (state.UTCDateRange)
		state.queryParams.dateRange = [convertLocalDate(state.UTCDateRange[0]), convertLocalDate(state.UTCDateRange[1])];
	else
		state.queryParams.dateRange = [];
}

// 查询操作
const handleQuery = async () => {
	state.loading = true;
	await formatLocalDate();
	if (!state.queryParams.operatorPlatform)
		state.queryParams.operatorPlatform = undefined;
	if (!state.queryParams.province)
		state.queryParams.province = undefined;

	const res = await SysDiRequestSmsRecordApi().queryRecord(state.queryParams);
	state.data = res.data.result.items ?? [];
	state.total = res.data.result?.total;
	state.loading = false;
	var reg = /^(\d{3})\d{4}(\d{4})$/;
	state.data.forEach((item)=>{
		item.phoneC = item.phone.replace(reg, `$1${'*'.repeat(4)}$2`);
	})
};

// 鼠标划入电话单元格时
const TransferIn = (row, column, cell, event) => {
	if (column.property == 'phoneC') {
		row.phoneC = row.phone;
		// console.log(row, column, cell, event);
	}
};

// 鼠标移出电话单元格时
const mark = (row, column, cell, event) =>{
	if (column.property == 'phoneC') {
		var reg = /^(\d{3})\d{4}(\d{4})$/;
		row.phoneC = row.phoneC.replace(reg, `$1${'*'.repeat(4)}$2`);
	}
};

// 重置操作
const resetQuery = () => {
	state.queryParams.pid = undefined;
	state.queryParams.phone = undefined;
	state.queryParams.province = undefined;
	state.queryParams.productName = undefined;
	state.queryParams.operatorPlatform = undefined;
	state.queryParams.sendSMSData = undefined;
	state.queryParams.verifySMSData = undefined;
	handleQuery();
};

const exportExcel = async () => {
    state.loading = true;
    await formatLocalDate();
    if (!state.queryParams.operatorPlatform)
        state.queryParams.operatorPlatform = undefined;
    if (!state.queryParams.province)
        state.queryParams.province = undefined;

    await SysDiRequestSmsRecordApi().exportExcel(state.queryParams).then((res) => {
        const fileName = getFileName(res.headers);
        downloadByData(res.data as any, fileName);
        state.loading = false;
    });
};

// 详情
const delDiBusiness = (row: any) => {
	state.editTitle = '详情';
	editDieditDiRequestSmsRecordRef.value?.openDialog(row);
};


// 业务列表
const customerDictQuery = async () => {
	await SysDiCustomerApi().queryAll({}).then((res) => {
		if (res.data.resCode === '0000')
			state.customerDict = res.data.result ?? [];
	});
};

// 分页改变
const onHandleSizeChange = (val: number) => {
	state.queryParams.pageSize = val;
	handleQuery();
};

// 分页改变
const onHandleCurrentChange = (val: number) => {
	state.queryParams.pageNum = val;
	handleQuery();
};

// 日期不可选范围
const disabledDate = (time: Record<string, any>): boolean => {
    const today = new Date(); // 获取今天的日期
    today.setHours(0, 0, 0, 0); // 将时间设置为当天的零点
    return time.getTime() > today.getTime(); // 禁用今天之后的所有日期
}

</script>
